package com.zhainan.springmvc.view;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * Created by lvchang on 2016/10/2.
 */
public class ViewResolver implements View {

    @Override
    public void render(ModelAndView view, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        String viewName = view.getViewName();
        String content = loadTemplate(request.getServletContext().getResourceAsStream("/WEB-INF/" + viewName));
        content = parseTemplate(view.getModel(), content);
        writer.write(content);
    }

    private String loadTemplate(InputStream is) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder content = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        return content.toString();
    }

    private String parseTemplate(Map<String, String> model, String template) {

        for (Map.Entry<String, String> entry : model.entrySet()) {
            String key = entry.getKey();
            String matchedKey = String.format("\\$\\{%s\\}", key);
            template = template.replaceAll(matchedKey, entry.getValue());
        }
        return template;

    }

}